<template>
	<view class="layout">
		<view class="navbar">
			<uni-icons type="back" size="30px" color="black" @click="onClickBack"></uni-icons>
			<text v-if="!isMixMode">第{{currentPage}}组</text>
			<text v-else>{{mixGround}}混合</text>
			<uni-icons type="back" size="30px" color="transparent"></uni-icons>
		</view>
		<view class="countdown">
			学习倒计时：{{ countdownStore.formattedTime }}
		</view>
		<view class="content">

			<view v-if="isCutMode" v-for="(item, index) in showWordsList" :key="item.number">
				<view class="cutRowItem">
					<view :class="[item.number == selectedId ? 'active-textItem' : 'textItem']"  @click="onClickItem(item.number, item.word)">
						<text>{{item.word}}</text>
						<text v-if="selectedId === item.number && showTranslation">{{item.meaning}}</text>
					</view>
					<uni-icons type="clear" size="50" @click="cutPaperBox(index)"></uni-icons>
				</view>
			</view>
			
			<view v-else v-for="(item, index) in showWordsList" :key="item.number">
				<view class="judgeRowItem">
					<view :class="[item.number == selectedId ? 'active-textItem' : 'textItem']" @click="onClickItem(item.number, item.word)">
						<text>{{item.word}}</text>
						<text v-if="selectedId === item.number && showTranslation">{{item.meaning}}</text>
					</view>
					<uni-icons type="checkbox-filled" size="50" color="#18BB7C" @click="onClickYes(index)"></uni-icons>
					<uni-icons type="clear" size="50" color="#F6465D" @click="onClickNo(index)"></uni-icons>
				</view>
			</view>
			
		</view>
		<view class="boxRow">
			
			<view class="leftBox" @click="" v-if="!isCutMode">
				<uni-icons custom-prefix="iconfont" type="icon-box" size="80" color="#18BB7C"></uni-icons>
				<text>{{yesCount}}</text>
			</view>
			
			
			<view class="centerBox" @click="onClickCenterBox">
				<uni-icons custom-prefix="iconfont" type="icon-box" size="100" color="#464646"></uni-icons>
				<text>{{centerCount}}</text>
			</view>
			
			
			<view class="rightBox" @click="" v-if="!isCutMode">
				<uni-icons custom-prefix="iconfont" type="icon-box" size="80" color="#F6465D"></uni-icons>
				<text>{{noCount}}</text>
			</view>
			
		</view>

		<uni-popup ref="endDialog" type="center" :is-mask-click="false">
			<view class="endDialog">
				<view class="retest" @click="onRetest">
					重新检测
				</view>
				<view class="next" @click="nextGroup" v-if="(!isCutMode && isFirst && !isEnd) || (isMixMode && !isEnd)">
					下一组
				</view>
				<view class="next" @click="nextGroup" v-if="(!isCutMode && isFirst && isEnd) || (isMixMode && isEnd)">
					返回
				</view>
				<view class="mixBtn" @click="onMixWords" v-if="!isMixMode && !isFirst">
					混组检查
				</view>
			</view>
		</uni-popup>
		
		<uni-popup ref="backDialog" type="center" :is-mask-click="false">
			<view class="backDialog">
				<view class="dialogContent">
					<view class="dialogTitle">
						温馨提示
					</view>
					<text>是否确认退出</text>
					<view class="btnRow">
						<view class="btnLeft" @click="onConfirmBack">
							确认
						</view>
						<view class="btnRight" @click="onCloseDialog">
							取消
						</view>
					</view>
				</view>
				<uni-icons type="clear" size="100rpx" @click="onCloseDialog"></uni-icons>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {ref, computed} from "vue";
	import {onLoad,onReady, onUnload} from '@dcloudio/uni-app';
	
	import { useStudyInfoStore } from '../../store';
	import { useCountdownStore } from '../../store';
	
	//获得store实例对象
	const studyInfoStore = useStudyInfoStore()
	
	const countdownStore = useCountdownStore()
	
	//当前所有生词
	let wordsList = ref([]);
	//当前展示的单词
	let showWordsList = ref([]);
	
	//属于当前页的单词
	let pageWordsList = ref([]);
	//截止当前页混合单词
	let mixWordsList = ref([]);
	
	//是否处于剪单词模式
	let isCutMode = ref(true);
	//是否进入混合模式
	let isMixMode = ref(false);
	
	let currentPage = 0;
	
	let mixGround = ref("");
	
	//计数
	let centerCount = ref(0);
	let yesCount = ref(0);
	let noCount = ref(0);
	
	const endDialog = ref(null);
	const backDialog = ref(null);
	
	//是否是第一页
	let isFirst = ref(false);
	//是否是最后一页
	let isEnd = ref(false);
	
	//选中的单词id
	let selectedId = ref(-1);
	//是否显示中文翻译
	let showTranslation = ref(false);
	
	function test(){
		isFirst.value = !isFirst.value;
		console.log(isFirst.value)
		console.log(isEnd.value)
	}
	
	onLoad((e)=>{
		//从studyInfoStore中获取选择单词列表
		let arr = studyInfoStore.studyWordsList;
		let wordBank = uni.getStorageSync(studyInfoStore.wordBankId)
		//根据number从词库中赛选单词
		arr.forEach((item)=>{
			wordsList.value.push(wordBank.find(word => word.number === item))
		})
		
		//正则表达式解析
		wordsList.value.map(item => {
			if(item.meaning.includes(".")){
				let regex = /(?<=\.{1})[^\.]+?(?=[,，；]|$)/g;
				let match = item.meaning.match(regex);
				item.meaning = match.join()
			}
		})
		
		currentPage = e.page;
		
		isFirst.value = JSON.parse(e.isFirst);
		isEnd.value = JSON.parse(e.isEnd);
		
		console.log(currentPage)
		console.log(isFirst.value)
		console.log(isEnd.value)
		
		initPageWords();
		// console.log(wordsList.value);
	})
	
	onReady(() => {
		// 监听倒计时结束事件
		uni.$on('countdownFinished', () => {
		  uni.showToast({
		    title: '倒计时结束',
		    icon: 'none'
		  })
		  if(studyInfoStore.studyMode === 0){
			  uni.$emit('finish');
			  uni.navigateBack({
				  delta: 1
			  });
		  } else if(studyInfoStore.studyMode === 1) {
			  // uni.redirectTo({
			  // 	url: "/pages/detection/detection"
			  // })
			  // uni.navigateBack({
				 //  success() {
					//   // uni.showLoading({
					//   // 	title:"正在前往检测",
					//   // 	mask:true
					//   // })
					//   setTimeout(() => {
					// 	// uni.showLoading({
					// 	// 	title:"正在前往检测",
					// 	// 	mask:true
					// 	// })
					// 	uni.redirectTo({
					// 		url: "/pages/detection/detection",
					// 		// success() {
					// 		// 	uni.hideLoading()
					// 		// }
					// 	})
						
					//   }, 300);
					  
				 //  	// uni.redirectTo({
				 //  	// 	url: "/pages/detection/detection"
				 //  	// })
				 //  }
			  // })
			  // uni.navigateBack()
		  }
		})
	})
	
	onUnload(() => {
	    // 移除监听事件
		uni.$off('countdownFinished');
	})
	
	function onClickItem(number, word) {
	    if (selectedId.value === number) {
	        showTranslation.value = !showTranslation.value;
	    } else {
	        showTranslation.value = false;
	    }
	    selectedId.value = number;
		
		// let tempWord = word.trim()
		let tempWord = word
		if(tempWord.includes('/')) {
			let regex = /(\b[A-Za-z.]+)\s*(?=\/)/g;
			tempWord = tempWord.match(regex)[0];
		} else if(tempWord.includes('(')) {
			let regex = /(\b[A-Za-z.]+)\s*(?=\()/g;
			tempWord = tempWord.match(regex)[0];
		}
	
		tempWord = tempWord.replace(/-+/g, ' ').trim()
		
	    voiceplay(tempWord);
	}
	
	//音频播放 type=0是英音，1是美音
	function voiceplay(key) {
	    uni.showLoading({
	        title: '加载中',
	    })
	    const innerAudioContext = uni.createInnerAudioContext();
	    innerAudioContext.autoplay = true;
	    // http://dict.youdao.com/dictvoice?type=0&audio=' + key; key 是需要发音的单词，链接就是有道词典的接口链接，返回就是一个音频，直接可以播放，可以直接在游览器打开。
	    innerAudioContext.src = 'http://dict.youdao.com/dictvoice?type=0&audio=' + key;
	    innerAudioContext.onPlay(() => {
	        console.log('开始播放');
	        uni.hideLoading();
	    });
	    innerAudioContext.onError((res) => {
	        console.log(res.errMsg);
	        console.log(res.errCode);
	        uni.hideLoading();
	    });
	    uni.hideLoading();
	}
	
	
	//混合多少组
	function getGrounds(n) {
		console.log(isEnd.value)
		if(isEnd.value) {
			mixGround.value = "全部"
		} else {
			let str = "第"
			for (let i = 1; i <= n; i++) {
			  if(i == n){
				  str = str.concat(`${i}组`)
			  } else {
				  str = str.concat(`${i},`)
			  }
			}
			mixGround.value = str
		}

	}
	
	function onClickBack(){
		backDialog.value.open();
	}
	
	function onConfirmBack(){
		uni.navigateBack();
	}
	
	function onCloseDialog(){
		backDialog.value.close();
	}
	
	function onClickCenterBox(){
		initJudgeWords();
	}
	
	//重置当前页单词
	function initPageWords(){
		const start = (currentPage - 1) * 5;
		const end = start + 5;
		pageWordsList.value = wordsList.value.slice(start, end);
		showWordsList.value = [...pageWordsList.value];
	}
	
	//重置当前页判断单词
	function initJudgeWords(){
		isCutMode.value = false;
		
		selectedId.value = -1;
		showTranslation.value = false;
		
		if(isMixMode.value){
			centerCount.value = mixWordsList.value.length;
			initJudgeMixWords();
		} else{
			centerCount.value = pageWordsList.value.length;
			initPageWords();
		}
		
		yesCount.value = 0;
		noCount.value = 0;
		
	}
	
	//点击了混组检查
	function onMixWords(){
		isCutMode.value = true;
		isMixMode.value = true;
		initCutMixWords();
		
		getGrounds(currentPage);
		endDialog.value.close();
	}
	
	//重置截止当前组混合单词
	function initCutMixWords(){
		const start = (currentPage - 1) * 5;
		const end = start + 5;
		mixWordsList.value = wordsList.value.slice(0, end);
		// isCutMode.value = false;
		centerCount.value = 0;
		yesCount.value = 0;
		noCount.value = 0;
		showWordsList.value = [...mixWordsList.value.splice(0, 5)];
	}
	
	//重置截止当前组混合单词
	function initJudgeMixWords(){
		const start = (currentPage - 1) * 5;
		const end = start + 5;
		mixWordsList.value = wordsList.value.slice(0, end);
		// isCutMode.value = false;
		centerCount.value = mixWordsList.value.length;
		yesCount.value = 0;
		noCount.value = 0;
		showWordsList.value = [...mixWordsList.value.splice(0, 5)];
		
		console.log(showWordsList.value);
	}
	
	
	//剪单词
	function cutPaperBox(index){
		showWordsList.value.splice(index, 1);
		changeShowWordsList();
		centerCount.value++;
	}
	//点击yes
	function onClickYes(index){
		showWordsList.value.splice(index, 1);
		changeShowWordsList();
		centerCount.value--;
		yesCount.value++;
	}
	//点击no
	function onClickNo(index){
		showWordsList.value.splice(index, 1);
		changeShowWordsList();
		centerCount.value--;
		noCount.value++;
	}
	
	//点击重新检测触发事件
	function onRetest(){
		endDialog.value.close();
		initJudgeWords();
	}
	
	//点击下一组触发事件
	function nextGroup(){
		uni.$emit('nextPage');
		uni.navigateBack();
	}
	
	function changeShowWordsList(){
		selectedId.value = -1;
		showTranslation.value = false;
		console.log(mixWordsList.value.length);
		if(mixWordsList.value.length != 0){
			showWordsList.value.push(mixWordsList.value.shift());
		}
		if(!isCutMode.value){
			if(showWordsList.value.length === 0){
				console.log(isMixMode.value)
				console.log(isFirst.value)
				endDialog.value.open();
			}
		}

	}
	
	// 计算当前页的数据
	// const paginatedData = computed(() => {
	//   const start = (currentPage - 1) * 5;
	//   const end = start + 5;
	//   return wordsList.value.slice(start, end);
	// });
</script>

<style lang="scss" scoped>
	.layout{
		background-color: #F5F5F5;
		height: 100vh;
		.navbar{
			background-color: #18BB7C;
			padding: 46px 16px 16px 16px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			text{
				font-size: 26px;
				font-weight: 500;
			}
		}
		.countdown{
			display: flex;
			justify-content: center;
			margin-top: 20rpx;
			font-size: 50rpx;
			color: #18BB7C;
		}
		.content{
			padding: 20rpx;
			overflow: hidden;
			height: 55vh;

			.cutRowItem{
				display: flex;
				flex-direction: row;
				gap: 20rpx;
				justify-content: space-between;
				align-items: center;
				.active-textItem{
					margin: 20rpx 0;
					padding: 20rpx;
					width: 100%;
					font-size: 24px;
					background-color: white;
					display: flex;
					border: 1px solid green;
					gap: 20rpx;
					flex-direction: column;
					justify-content: center;
					align-items: center;
				}
				.textItem{
					margin: 20rpx 0;
					padding: 20rpx;
					width: 100%;
					font-size: 24px;
					background-color: white;
					display: flex;
					gap: 20rpx;
					flex-direction: column;
					justify-content: center;
					align-items: center;
				}
			}
			.judgeRowItem{
				display: flex;
				flex-direction: row;
				gap: 5rpx;
				justify-content: space-between;
				align-items: center;
				.active-textItem{
					margin: 20rpx 0;
					padding: 20rpx;
					width: 100%;
					font-size: 24px;
					background-color: white;
					border: 1px solid green;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
				}
				.textItem{
					margin: 20rpx 0;
					padding: 20rpx;
					width: 100%;
					font-size: 24px;
					background-color: white;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
				}
			}

		}
		.boxRow{
			display: flex;
			justify-content: center;
			gap: 0rpx;
			padding: 0 0rpx;
			align-items: end;
			.centerBox{
				height: 100%;
				width: 100%;
				background-color: transparent;
				display: flex;
				position: relative;
				justify-content: center;
				align-items: center;
				text{
					padding-top: 30rpx;
					position: absolute;
					font-size: 30px;
				}
			}

			.leftBox{
				height: 100%;
				width: 100%;
				background-color: transparent;
				display: flex;
				position: relative;
				justify-content: center;
				align-items: center;
				text{
					padding-top: 30rpx;
					position: absolute;
					font-size: 30px;
				}
			}
			

			.rightBox{
				height: 100%;
				width: 100%;
				background-color: transparent;
				display: flex;
				position: relative;
				justify-content: center;
				align-items: center;
				text{
					padding-top: 30rpx;
					position: absolute;
					font-size: 30px;
				}
			}
			
			
		}

		.endDialog{
			font-size: 24px;
			text-align: center;
			display: flex;
			flex-direction: column;
			gap: 20px;
			.retest{
				padding: 20rpx 0;
				width: 350rpx;
				background-color: orange;
				border-radius: 50rpx;
			}
			.next, .mixBtn {
				padding: 20rpx 0;
				width: 350rpx;
				background-color: #18BB7C;
				background-color: springgreen;
				border-radius: 50rpx;
			}
		}
		
		.backDialog{
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 60rpx;
			.dialogContent{
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 40rpx;
				background-color: white;
				border-radius: 50rpx;
				.dialogTitle{
					margin-bottom: 80rpx;
					padding: 15rpx 50rpx;
					border-radius: 50rpx;
					background-color: #18BB7C;
					color: white;
					font-size: 24px;
				}
				text{
					color: red;
					font-size: 24px;
				}
				.btnRow{
					display: flex;
					flex-direction: row;
					gap: 20rpx;
					color: white;
					font-size: 26px;
					margin-top: 50rpx;
					.btnLeft{
						padding: 20rpx 50rpx;
						background-color: #18BB7C;
						border-radius: 50rpx;
					}
					.btnRight{
						padding: 20rpx 50rpx;
						background-color: orange;
						border-radius: 50rpx;
					}
				}
			}
			
		}
	}
</style>
